import { Directive,EventEmitter,HostListener,OnInit,Output,OnDestroy,Input } from '@angular/core';
import {Subject} from "rxjs/Subject";
import  "rxjs/add/operator/debounceTime";
import { Subscription } from "rxjs/Subscription";
//对于 RxJS 中 Observables 和 Subject 对象，一旦我们不再使用它们，
//我们必须取消订阅事件。如果我们没有执行取消订阅操作，有可能会出现内存泄漏。
@Directive({
  selector: '[appMyDebounceClick]'
})
export class MyDebounceClickDirective  implements OnInit,OnDestroy{
  @Input() debounceTime=500;
  @Output("appMyDebounceClick") callClick=new EventEmitter();
  private clicks=new Subject<any>();
  private subscription: Subscription;
  constructor() { }
  ngOnInit(){
    this.subscription=this.clicks.debounceTime(this.debounceTime).subscribe(e=>{
      this.callClick.emit(e);
    })
  }
  ngOnDestroy(){
    this.subscription.unsubscribe();
  }
  @HostListener('click',['$event']) click(event:MouseEvent){
    event.preventDefault();
    event.stopPropagation();
    this.clicks.next(event);
  }

}
